<template>
  <div class="com-container">
    <div class="com-chart" ref="hot_ref"></div>
    <span :style="comStyle" @click="changeHotType(-1)" class="iconfont arr-left">&#xe6ef;</span>
    <span :style="comStyle" @click="changeHotType(1)" class="iconfont arr-right">&#xe6ed;</span>
    <span :style="comStyle" class="hot-title">{{catTitle}}</span>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getThemeValue } from '@/utils/theme_utils'
export default {
  data () {
    return {
      chartInstance: null,
      allData: null,
      hotType: 0, // 当前的热门分类
      titleFontSize: null
    }
  },
  created () { // 组件创建后 - 函数
    // 组件创建时，注册socket的回调函数
    this.$socket.registerCallBack('hotData', this.getData)
  },
  mounted () {
    this.initChart()
    // this.getData()
    // 发送数据给服务器，告诉服务器，这个客户端需要数据
    this.$socket.send({
      action: 'getData',
      socketType: 'hotData',
      chartName: 'hotproduct',
      value: ''
    })
    this.resizeChart()
    window.addEventListener('resize', this.resizeChart)
  },
  destoryed () {
    // 移除监听
    window.removeEventListener('resize', this.resizeChart)
    // 组件销毁时，注销socket的回调函数
    this.$socket.unregisterCallBack('hotData')
  },
  computed: {
    catTitle () {
      if (this.allData) {
        return this.allData[this.hotType].name
      }
      return ''
    },
    comStyle () {
      return {
        fontSize: this.titleFontSize + 'px',
        // color: this.theme === 'chalk' ? '#fff' : '#333'
        color: getThemeValue(this.theme).titleColor
      }
    },
    ...mapState(['theme'])
  },
  methods: {
    // 1.初始化echarts对象
    initChart () {
      this.chartInstance = this.$echarts.init(this.$refs.hot_ref, this.theme)
      const initOption = {
        title: {
          text: '▎热销商品占比',
          textStyle: {
            fontSize: 36
          },
          left: 20,
          top: 20
        },
        legend: {
          top: '15%',
          icon: 'circle'
        },
        tooltip: {
          show: true,
          formatter: (arg) => {
            const thirdType = arg.data.children
            let total = 0
            thirdType.forEach(item => {
              total += item.value
            })
            let thirdStr = ''
            thirdType.forEach(item => {
              thirdStr += `${item.name}：${parseInt(item.value / total * 100) + '%'}<br/>`
            })
            return thirdStr
          }
        },
        series: [
          {
            type: 'pie',
            label: {
              show: false
            },
            emphasis: {
              label: {
                show: true
              },
              labelLine: {
                show: false
              }
            }
          }
        ]
      }
      this.chartInstance.setOption(initOption)
    },

    // 2.获取数据
    getData (res) {
      // 获取数据
      // const { data: res } = await this.$http.get('hotproduct')
      this.allData = res
      this.updateChart()
    },

    // 3.更新数据
    updateChart () {
      // 处理图表需要的数据
      const legendArr = this.allData[this.hotType].children.map(item => {
        return item.name
      })
      const seriesArr = this.allData[this.hotType].children.map(item => {
        return {
          name: item.name,
          value: item.value,
          children: item.children
        }
      })
      const dataOption = {
        legend: {
          data: legendArr
        },
        series: {
          data: seriesArr
        }
      }
      this.chartInstance.setOption(dataOption)
    },

    // 4.分辨率适配
    resizeChart () {
      const titleFontSize = this.titleFontSize = this.$refs.hot_ref.offsetWidth / 100 * 3.6
      const resizeOption = {
        title: {
          textStyle: {
            fontSize: titleFontSize
          }
        },
        legend: {
          itemWidth: titleFontSize,
          itemHeight: titleFontSize,
          itemGap: titleFontSize / 2,
          textStyle: {
            fontSize: titleFontSize / 1.5
          }
        },
        series: [{
          radius: titleFontSize * 4.5,
          center: ['50%', '60%']
        }]
      }
      this.chartInstance.setOption(resizeOption)
      this.chartInstance.resize()
    },

    // 5.切换一级分类
    changeHotType (num) {
      console.log(this.hotType)
      this.hotType = this.hotType + num
      if (this.hotType > this.allData.length - 1) {
        this.hotType = 0
      }
      if (this.hotType < 0) {
        this.hotType = this.allData.length - 1
      }
      this.updateChart()
    }
  },
  watch: {
    theme () {
      console.log('主题切换了')
      // 1.销毁当前图表
      this.chartInstance.dispose()
      // 2.重新注册当前图表 -- 以最新主题渲染图表
      this.initChart()
      this.resizeChart()
      this.updateChart()
    }
  }
}
</script>

<style lang="less" scoped>
.arr-left, .arr-right{
  position: absolute;
  top: 60%;
  z-index: 99;
  font-size: 50px;
  transform: translateY(-50%);
  cursor: pointer;
}
.arr-left{
  left: 20%;
}
.arr-right{
  right: 20%;
}
.hot-title{
  position: absolute;
  bottom: 10%;
  right: 10%;
  z-index: 99;
}
</style>
